import axios from 'axios'
import { getStorage, removeStorage } from 'utils/storage'
import history from './history'
import { message } from 'antd'

const request = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 请求配置的统一处理
    const token = getStorage('jikenyuan_token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token.token
    }
    return config
  },
  (error) => {
    // 请求错误
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 响应成功
    return response.data
  },
  (error) => {
    // 响应失败
    if (error.response?.status === 401) {
      // token过期
      removeStorage('jikenyuan_token')
      // 跳转到登录页
      history.push('/login')
      message.warning('用户信息已过期')
    }
    return Promise.reject(error)
  }
)

export default request
